const fs = require("fs")
const path = require("path")
const vueDocs = require('vue-docgen-api')
let vueFileList = []
let startPath = './pages'
let fileNumber = 0

let fileRead = function (filePath) {
  let _filePath = path.resolve(filePath)
  let _fileList = fs.readdirSync(_filePath)
  fileNumber = fileNumber + _fileList.length
  if(_filePath) {
    //console.log("解析路径:",_filePath)
    _fileList.forEach((filename,index)=>{
      //根据文件路径获取文件信息，返回一个fs.Stats对象
      
      let fsStat = fs.statSync(_filePath)
      if(fsStat){
        ((stats) =>{
            // //console.log(filename)
            //获取当前文件的绝对路径
            let filedir = path.posix.join(filePath,filename);
            // const isFile = stats.isFile();//是文件
            
            let filenameArray = filename.split('.')
            if(filenameArray[filenameArray.length - 1] === 'vue'){
              
              vueDocs.parse('./' + filedir)
                  .then((doc) => {
                    fileNumber = fileNumber - 1
                    vueFileList.push(doc)
                    if(fileNumber === 0){
                      savePathNameJs()
                    }
                  }).catch((err) => {
                    console.error(err)
                  });

            } else if(filenameArray.length === 1) {
              fileNumber = fileNumber - 1
              const isDir = stats.isDirectory();//是文件夹
              if(isDir){
                fileRead(filedir)
              }
            } else {
              fileNumber = fileNumber - 1
            }
        })(fsStat)
      } else {
        console.warn('获取文件stats失败');
      }

    })
  } else {
    //console.log("没有找到该文件")
    //console.log("错误URL：",url)
  }

}

function savePathNameJs(params) {
  // //console.log('save');
  // //console.log(vueFileList);
  let pathMap = ''
  vueFileList.forEach((item)=>{
    pathMap = pathMap + `${item.displayName}:"${item.description}", "${item.description}":"${item.displayName}", `
  })
  let content = `
    let pathMap = {
      ${pathMap}
    }
    export {pathMap}
  `
  fs.writeFile('./pathMap.js',content,'utf8',function(error){
      if(error){
          //console.log(error);
          return false;
      }
      //console.log('写入成功');
  })
}


fileRead(startPath)

// vueDocs.parse('./pages/managePaper/index.vue')
//   .then((doc) => {
//     //console.log(doc)
//   }).catch((err) => {
//     console.error(err)
//   });


